package org.rslai.tcedit.dao.hibernate;

import java.util.List;
import org.rslai.tcedit.dao.ProductUserDao;
import org.rslai.tcedit.domain.Page;
import org.rslai.tcedit.domain.ProductUser;
import org.rslai.tcedit.exception.ApplicationException;

/**
 * ProductUserDao 的实现类
 * 
 * @author rslai
 * 
 * @spring.bean id="productUserDao"
 */
public class ProductUserImpl extends GenericHibernateDao<ProductUser> implements ProductUserDao {

	public ProductUserImpl() {
		super(ProductUser.class);
	}

	/**
	 * 创建一个  ProductUser 信息。覆盖 GenericHibernateDao 中的 create 方法。
	 * 
	 * @param productUser ProductUser对象
	 */
	public void create(ProductUser productUser) {
		ProductUser tmpProductUser = (ProductUser) queryForObject(
				"from ProductUser as a where a.product.id=? and a.user.id=?",
				new Object[] { productUser.getProduct().getId(), productUser.getUser().getId() }
		);
		if (tmpProductUser != null) {
			throw new ApplicationException("此产品中已有此用户，请重新输入。");
		}

		hibernateTemplate.save(productUser);
	}
	
	/**
	 * 更新一个 ProductUser 信息。覆盖 GenericHibernateDao 中的 update 方法。
	 * 
	 * @param productUser ProductUser 对象
	 */
	public void update(ProductUser productUser) {
		ProductUser tmpProductUser = (ProductUser) queryForObject(
				"from ProductUser as a where a.product.id=? and a.user.id=? and a.id!=?",
				new Object[] { productUser.getProduct().getId(), productUser.getUser().getId(), productUser.getId() }
		);
		if (tmpProductUser != null) {
			throw new ApplicationException("此产品中已有此用户，请重新输入。");
		}

		hibernateTemplate.update(productUser);
	}

    private static final String QUERY_USER_NAME_ASC = "from ProductUser as a where a.product.id=? AND a.user.username LIKE ? AND a.user.realName LIKE ? AND a.user.email LIKE ? order by a.user.username";
    private static final String QUERY_USER_NAME_DESC = "from ProductUser as a where a.product.id=? AND a.user.username LIKE ? AND a.user.realName LIKE ? AND a.user.email LIKE ? order by a.user.username desc";

	@SuppressWarnings("unchecked")
	public List<ProductUser> query(String productID, Page page, String username, String realName, String email, boolean asc) {
		return queryForList(
				"select count(*) from ProductUser as a where a.product.id=? AND a.user.username LIKE ? AND a.user.realName LIKE ? AND a.user.email LIKE ?",
				asc ? QUERY_USER_NAME_ASC : QUERY_USER_NAME_DESC,  
				new Object[] { productID, username, realName, email},
				page
		);
	}

	@SuppressWarnings("unchecked")
	public List<ProductUser> query(String productID) {
		return queryForList(
				"from ProductUser as a where a.product.id=?",
				new Object[] { productID });
	}

	@SuppressWarnings("unchecked")
	public List<ProductUser> query(String productID, String userID) {
		return queryForList(
				"from ProductUser as a where a.product.id=? AND a.user.id=?",
				new Object[] { productID, userID });
	}

}
